/**
 * 核心技术支持
 * IT渠道网 小程序商城
 * 13873174181 微信同号
 */
import {Order} from '../order/order-model.js';
import {Cart} from '../cart/cart-model.js';
import {Address} from '../../utils/address.js';
var order = new Order();
var cart = new Cart();
var address = new Address();

Page({
    data: {
        fromCartFlag: true, //是否购物车订单, 已生成就不是了
        restUrl: order.getUrl(),
        addressInfo: null,
        //productsArr 已选商品
        //account     总价
        //orderStatus 状态0
        //id          订单id my订单id
        showPayment: 0, //支付方式
        payment: 1,
        payList: [
            {'id':1, 'icon':'icon-share-wechat', 'name':'在线支付'},
            {'id':2, 'icon':'icon-user-yhq', 'name':'货到付款'}
        ],
        productsArr: [],
        msgList: [] //封装留言
    },
    /*
     * 订单数据来源 购物车下单 旧订单
     */
    onLoad: function(options) {
        var that = this,
            flag = options.from == 'cart'; // 首次生成订单cart  my中order
        that.data.fromCartFlag = flag; // 来自于购物车true
        that.data.orderStatus = 0; //订单状态0未支付
        // 来自于购物车,已选商品展示
        if (flag) {
            //获取店铺已领取优惠券 *
            var arr = cart.getCartDataFromLocal(true), account = 0;
            console.log(0, arr)
            for (var i in arr) {
                //计算优惠券最大
                var total = 0, //商品总额
                    itemList = arr[i].orderItemList;
                for(var j in itemList){
                    total += Number(itemList[j].price);
                    account += Number(itemList[j].totalFee);
                }
                cart.findPayCoupon(arr[i].sellerId, (data)=>{
                    if (data) {
                        var couponList = data;
                        //筛选
                        var fullPrice = 0,
                            lessPrice = 0;
                        for(var y in couponList){
                            var full = Number(couponList[y].fullPrice),
                                less = Number(couponList[y].lessPrice);
                            if (total >= full) {
                                if (lessPrice < less) {
                                    lessPrice = less;
                                    arr[i].couponId = couponList[y].id;
                                }
                            }
                        }
                        arr[i].couponSel = lessPrice;
                        account = (account-lessPrice).toFixed(2);
                        // 赋值重点
                        that.setData({
                            productsArr: arr,
                            account: account
                        })
                    }
                })
            }
            // 缓存无,获取设置默认地址
            if (!address.getAddressFromLocal()) {
                address.getAddress((res)=>{
                    for (let i in res) {
                        if (res[i].df==1) {
                            that._bindAddressInfo(res[i]);
                            address.execSetStorageSync(res[i]);
                        }
                    }
                })
            }
        }else{
            // my订单id
            that.data.id = options.id
        }
    },
    /*
     * 数据处理
     */
    onShow: function() {
        // 获取已选缓存地址
        var addressInfo = address.getAddressFromLocal();
        this._bindAddressInfo(addressInfo);
    },
    /*
     * 绑定地址信息
     */
    _bindAddressInfo: function(addressInfo) {
        this.setData({
            addressInfo: addressInfo
        });
    },
    /*
     * 下单和付款
     */
    pay: function() {
        if(!this.data.addressInfo){
            this.showTips('下单提示','请填写您的收货地址');
            return;
        }
        if(this.data.orderStatus==0){
            this._firstTimePay(); // 购物车创建订单并支付,首次订单
        }else{
            this._oneMoresTimePay(); // my订单支付
        }
    },
    /*
     * 第一次支付 先下单再支付
     */
    _firstTimePay: function() {
        var that = this,
            order = new Order(),
            orderInfo = {};
        // 封装地址,订单产品
        var address = this.data.addressInfo;
        address['paymentType'] = this.data.payment;
        orderInfo['orderInfo'] = address;
        orderInfo['cartList'] = this.data.productsArr;
        orderInfo['msgList'] = this.data.msgList;
        // 1生成订单号
        order.doOrder(orderInfo, (data)=>{
            // 订单生成成功
            if(data.pass) {
                // 清除已生成订单的已选商品
                that.deleteProducts();
                // 更新订单状态
                var id = data.tradeNo; // 支付日志号,多订单
                that.data.id = id; // 返回时,获取订单数据
                that.data.fromCartFlag = false; // 已生成订单
                // 2开始支付
                that._execPay(id);
            }else{
                that._orderFail(data) // 下单失败, 打印失败信息
            }
        })
    },
    /*
     * 提示窗口
     */
    showTips: function(title,content,flag) {
        wx.showModal({
            title: title,
            content: content,
            showCancel: false,
            success: function(res) {
                if(flag) {
                    wx.switchTab({
                        url: '/pages/my/my'
                    });
                }
            }
        });
    },
    /*
     * 下单失败
     */
    _orderFail: function(data) {
        var nameArr=[],
            name='',
            str='',
            pArr=data.pStatusArray;
        for(let i=0;i<pArr.length;i++){
            if(!pArr[i].haveStock){
                name=pArr[i].name;
                if(name.length>15){
                    name = name.substr(0,12)+'...';
                }
                nameArr.push(name);
                if(nameArr.length>=2){
                    break;
                }
            }
        }
        str+=nameArr.join('、');
        if(nameArr.length>2){
            str+=' 等';
        }
        str+=' 缺货';
        wx.showModal({
            title: '下单失败',
            content: str,
            showCancel: false,
            success: function(res) {
            }
        });
    },
    /*
     * 再次次支付
     */
    _oneMoresTimePay: function() {
        this._execPay(this.data.id);
    },
    /*
     * 开始支付 支付日志号id
     */
    _execPay: function(id) {
        if(!order.onPay) {
            this.showTips('支付提示','本产品仅用于演示，支付系统已屏蔽',true); // 屏蔽支付，提示
            return;
        }
        var that = this;
        // 支付是否成功
        order.execPay(id, true, (statusCode) => {  // 2生成图成功支付 1生成失败或x图片 0不能支付(商品缺货)
            if(statusCode!=0){
                // 支付结果页面: 成功或失败
                wx.navigateTo({
                    url: '../pay-result/pay-result?id=' + id + '&flag=' + statusCode + '&from=order'
                });
            }
        });
    },
    /*
     * 将已经下单的商品从购物车删除
     */
    deleteProducts: function() {
        var ids = [], 
            arr = this.data.productsArr;
        for (var i in arr) {
            var list = arr[i].orderItemList;
            for (var j in list) {
                ids.push(list[j].itemId); 
            }
        }
        cart.delete(ids);
    },
    /*
     * 商品详情
     */
    onProductsItemTap: function(event) {
        var id = cart.getDataSet(event, 'id');
        wx.navigateTo({
            url: '../product/product?id=' + id
        })
    },
    /*
     * 支付方式
     */
    showPayment: function() {
        this.setData({
            showPayment: 1
        })
    },
    payPicker: function(e) {
        var id = order.getDataSet(e,'id');
        this.setData({
            payment: id,
            showPayment: 0
        })
    },
    payClose: function() {
        this.setData({
            showPayment: 0
        })
    },
    goToAddress: function() {
        wx.navigateTo({
            url: "/pages/address-picker/address-picker"
        })
    },
    /**
     * 失去焦点, 保存到历史
     */
    inputBlur: function(e) {
        console.log(15, e)
        var sellerId = e.currentTarget.dataset.sid,
            message = e.detail.value;
        //封装留言
        var msgList = this.data.msgList;
        if (msgList.length == 0) {
            msgList.push({'sellerId':sellerId,'message':message});
        }
        for(var i in msgList){
            if (sellerId == msgList[i].sellerId) {
                msgList[i].message = message;
            } else {
                msgList.push({'sellerId':sellerId,'message':message});
            }
        }
        this.setData({
            msgList: msgList
        })
    }
})